package com.jjh.service.impl;

import com.jjh.consts.Result;
import com.jjh.mapper.FlavourMapper;
import com.jjh.pojo.Flavour;
import com.jjh.service.FlavourService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class FlavourServiceImpl implements FlavourService {

    @Resource
    private FlavourMapper flavourMapper;


    @Override
    public Result getAll() {

        List<Flavour> flavours = flavourMapper.getAll();

        return Result.ok(flavours);
    }

    /**
     * 添加口味
     * @param flavour
     * @return
     */
    @Override
    public Result addOne(Flavour flavour) {
        if(ObjectUtils.isEmpty(flavour)||"".equals(flavour.getFlavour())){
            return Result.error("不能为空");
        }
        String flavourName = flavour.getFlavour().trim();
        //先查询看看有没有
        Flavour flavour1 = flavourMapper.getByName(flavourName);
        if(!ObjectUtils.isEmpty(flavour1)){
            return Result.error("该口味已经存在！");
        }
        //去掉空格
        flavour.setFlavour(flavourName);
        //不存在就可以添加了!
        int row =  flavourMapper.insertOne(flavour);
        if(row>0){
            return Result.ok("添加成功");
        }else{
            log.error("添加口味失败:{}",flavour);
            return Result.error("添加失败");
        }
    }

    /**
     * 根据id修改口味
     * @param flavour
     * @return
     */
    @Override
    public Result updateOne(Flavour flavour) {
        if(ObjectUtils.isEmpty(flavour)||"".equals(flavour.getFlavour())){
            return Result.error("不能为空");
        }
        String flavourName = flavour.getFlavour().trim();
        Flavour flavour1 = flavourMapper.getByName(flavourName);
        //判断是否是其他的口味
        if(!ObjectUtils.isEmpty(flavour1)&& !Objects.equals(flavour1.getId(), flavour.getId())){
            return Result.error("该口味已经存在！");
        }
        flavour.setFlavour(flavourName);
        //修改口味
        int row =  flavourMapper.updateById(flavour);
        if(row>0){
            return Result.ok("修改成功");
        }else{
            log.error("添加口味失败:{}",flavour);
            return Result.error("修改失败");
        }

    }

    @Override
    public Result deleteByIds(List<Integer> ids) {

       int rows =  flavourMapper.deleteByIds(ids);
        if(rows>0){
            return Result.ok("删除成功");
        }else{
            log.error("删除口味失败:{}",ids);
            return Result.error("删除失败");
        }

    }
}
